package SparkStream
import org.apache.kafka.clients.producer.{KafkaProducer, ProducerConfig, ProducerRecord}
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.SparkConf
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark.streaming.kafka010.KafkaUtils
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.{Seconds, StreamingContext}

import java.util.HashMap

object demo6{

  def main(args: Array[String]): Unit = {
    // 1） 构建sparkconf 本地运行，运行应用程序名称
    val conf = new SparkConf().setMaster("local[*]").setAppName("helloStream")
    // StreamingContext 需要导入依赖
    // spark streaming 可以进行流式处理，微批次处理，间隔2秒
    val ssc = new StreamingContext(conf, Seconds(2))

    // spark 输出红色 info信息 --> error
    ssc.sparkContext.setLogLevel("error")

    // 3） kafka 配置 broker，key value，group id，消费模式
    val kafkaParams = Map[String, Object](
      "bootstrap.servers" -> "192.168.121.129:9092",
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> "ypp11",
      "enable.auto.commit" -> (false: java.lang.Boolean)
    )
    // producer 配置项
    val property = new HashMap[String, Object]()
    property.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.121.129:9092")
    property.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer")
    property.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer")

    // 4） spark 链接kafka 订阅，topic，streamingcontext
    // topic name
    val topicName = Array("supermarket")
    val streamRdd = KafkaUtils.createDirectStream[String, String](
      ssc,
      PreferConsistent,
      Subscribe[String, String](topicName, kafkaParams)
    )

    // 数据处理逻辑
    val result = streamRdd.map(_.value())
      .map(line => {
        val fields = line.split("\t")
        (fields(0), fields(1), fields(4)) // (productId, productName, status)
      })
      .map(record => (record._1 + "," + record._2 + "," + record._3, 1)) // (productId\tproductName\tstatus, 1)
      .reduceByKeyAndWindow(_ + _, Seconds(2), Seconds(2))

    result.foreachRDD(rdd => {
      if (!rdd.isEmpty()) {
        rdd.foreach(record => {
          println(s"${record._1},${record._2}")
          // 创建新的客户端并发送数据到另一个topic
          val producer = new KafkaProducer[String, String](property)
          producer.send(new ProducerRecord[String, String]("data5", record.toString()))
          producer.close()
        })
      }
    })

    // 6）开启ssc，监控kafka数据
    ssc.start()
    ssc.awaitTermination()
  }
}